package com.keymozy.controller.interceptor;

import com.keymozy.annotaion.NoAuthentication;
import com.keymozy.pojo.Staff;
import com.keymozy.util.CookieUtil;
import com.keymozy.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
//验证token
public class VerifyInterceptor implements HandlerInterceptor {
    @Value("${openVerify}")
    private boolean openVerify;
//    @Value("${client.url}")
//    private String url;

//    @Autowired
//    private RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        log.info("进入了Verify拦截器"+request.getRequestURI());
        log.info("进入了Verify拦截器"+request.getMethod());
        log.info("进入了Verify拦截器"+request.getContextPath());
        log.info("进入了Verify拦截器"+request.getPathInfo());
        log.info("进入了Verify拦截器"+request.getServletPath());
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            NoAuthentication anonymousAccess = method.getMethodAnnotation(NoAuthentication.class);
            // 如果访问的方法上有AnonymousAccess注解，则匿名访问不拦截
            if (anonymousAccess != null) {
                return true;
            }
        }
        if (!openVerify){
            log.info("token验证未开启");
            Cookie cookie = CookieUtil.getCookie(request.getCookies(), "token");
            String token = cookie.getValue();
            TokenUtil.data.set(TokenUtil.getObj(token,Staff.class));
            return true;
        }
//        HttpSession session = request.getSession();
//        String isLogin = (String) session.getAttribute("isLogin");
        //先用个map存取每个用户ip是否已经登录过，后面可能会改成redis存取
        String isLogin = TokenUtil.ipLogin.get(request.getRemoteAddr());
        request.setAttribute("status",401);
        log.info("isLogin:"+isLogin);
        if (isLogin==null||"".equals(isLogin)){
            log.info("还没登录");
            log.info("session data is null");
            return redirect(response);
        }
//        else {
//            int flag = (int) isLogin;
//            if (flag==0){
//                log.info("还没登录");
//                return redirect(response);
//            }
//        }
        //获取token
        Cookie cookie = CookieUtil.getCookie(request.getCookies(), "token");
        if (null==cookie){
            log.info("没有token");
            return redirect(response);
        }
        String token = cookie.getValue();
        //检查token是否被修改过
        if (!token.split("\\.")[1].equals(isLogin)){
            log.info("token被修改过");
            return redirect(response);
        }
        //验证token是否正确，有没有被修改过
        if (!TokenUtil.verify(token)){
            log.info("token验证失败");
            return redirect(response);
        }
        //保存一份用户数据,给后面进入到controller使用
        TokenUtil.data.set(TokenUtil.getObj(token,Staff.class));
        return true;
    }

    private boolean redirect(final HttpServletResponse response) throws IOException {
        log.info("重定向了");
        response.setStatus(302);
//        response.sendRedirect(this.url);
       return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TokenUtil.data.remove();
    }
}
